import { createSlice, createAsyncThunk, Dispatch } from '@reduxjs/toolkit'
import {
  getCurrentSongInfo,
  getSongLyricInfo,
  getAlbumList
} from '..//service/player'
import { Lyric, parseLyric } from '@/utils/parse-lyric'
import { RootState } from '@/store'
import { Song } from '@/types/common-types'

interface IPlayerState {
  currentSong: Song
  playSongList: Song[]
  playSongIndex: number
  playMode: number
  lyrics: Lyric[]
  lyricIndex: number
}

export function seekLyric(id: number, dispatch: Dispatch) {
  getSongLyricInfo(id).then((res: any) => {
    let tLyric = ''
    const concatLyrics: Lyric[] = []
    const lyrics: Lyric[] = parseLyric(res.lrc.lyric)
    if (res.tlyric && res.tlyric.lyric) {
      tLyric = res.tlyric.lyric.replace(/\s/g, '')
    }
    // 是否为双语歌词
    if (tLyric.length) {
      const tLycs: Lyric[] = parseLyric(res.tlyric.lyric)
      lyrics.forEach((lyc) => {
        tLycs.forEach((tlyc) => {
          if (lyc.time === tlyc.time) {
            lyc = { ...lyc, text: `<p>${lyc.text}</p>` + `<p>${tlyc.text}</p>` }
          }
        })
        concatLyrics.push(lyc)
      })
      // console.log('双语:', concatLyrics)
      dispatch(changeLyricAction(concatLyrics))
    } else {
      // console.log('中文:', lyrics)
      dispatch(changeLyricAction(lyrics))
    }
  })
}

export const changePlayingSongAction = createAsyncThunk<
  void,
  number,
  { state: RootState }
>('changePlayingSong', (id: number, { dispatch, getState }) => {
  let ids: number[] = []
  const newPlaySongList: Song[] = []
  const currentSong = getState().player.currentSong
  if (currentSong && currentSong.id === id) return
  let songs: Song[] = []
  if (id.toString().includes(',')) {
    const list = id.toString().split(',')
    list.forEach((item) => {
      ids.push(Number(item))
    })
  } else {
    ids = [id]
  }
  ids.forEach((id) => {
    getCurrentSongInfo(id).then((res: any) => {
      if (res.songs.length) {
        newPlaySongList.push(res.songs[0])
        songs = [...newPlaySongList]
        dispatch(changePlaySongIndexAction(0))
        dispatch(changePlaySongListAction(songs))
        dispatch(changeCurrentSongAction(songs[0]))
      }
    })
  })
  dispatch(changePlaySongListAction([]))
  seekLyric(ids[0], dispatch)
})

export const changeAlbumListSongAction = createAsyncThunk<
  void,
  number,
  { state: RootState }
>('changeAlbumListSong', (id: number, { dispatch }) => {
  dispatch(changePlaySongListAction([]))
  getAlbumList(id).then((res: any) => {
    if (res.songs.length) {
      const song = res.songs[0]
      dispatch(changeCurrentSongAction(song))
      dispatch(changePlaySongIndexAction(0))
      dispatch(changePlaySongListAction(res.songs))
      seekLyric(song.id, dispatch)
    }
  })
})

// 添加新的歌曲到列表
export const addSongToListAction = createAsyncThunk<
  void,
  number,
  { state: RootState }
>('addToPlayList', (id: number, { dispatch, getState }) => {
  const playSongList = getState().player.playSongList
  const fIndex = playSongList.findIndex((item) => item.id === id)
  let song = null
  if (fIndex < 0) {
    getCurrentSongInfo(id).then((res: any) => {
      if (res.songs.length) {
        song = res.songs[0]
        // console.log('song:', song)
        const newPlaySongList = [...playSongList]
        newPlaySongList.push(song)
        dispatch(changePlaySongListAction(newPlaySongList))
      }
    })
  }
})
// 切换歌曲(上一首/下一首)
export const toggleMusicAction = createAsyncThunk<
  void,
  boolean,
  { state: RootState }
>('toggleMusic', (isNext, { dispatch, getState }) => {
  const player = getState().player
  const playIndex = player.playSongIndex
  const playMode = player.playMode
  const playList = player.playSongList
  const len = playList.length - 1
  const lenb = playList.length
  let newIndex = playIndex
  // 随机播放
  if (playMode === 1) {
    newIndex = Math.floor(Math.random() * lenb)
  } else {
    newIndex = isNext ? playIndex + 1 : playIndex - 1
    if (newIndex > len) newIndex = 0
    if (newIndex < 0) newIndex = len
  }
  // console.log('playList:', playList)
  if (!playList.length) return
  const song = playList[newIndex]
  dispatch(changeCurrentSongAction(song))
  dispatch(changePlaySongIndexAction(newIndex))
  seekLyric(song.id, dispatch)
})
// 修改歌曲列表
export const playNewSongListAction = createAsyncThunk<
  void,
  Song[],
  { state: RootState }
>('playNewSongList', (songList, { dispatch }) => {
  const song = songList[0]
  dispatch(changePlaySongIndexAction(0))
  dispatch(changeCurrentSongAction(song))
  dispatch(changePlaySongListAction(songList))
  seekLyric(song.id, dispatch)
})

// 清空歌曲列表
export const clearPlaySongListAction = createAsyncThunk<void>(
  'clearPlaySongList',
  (_, { dispatch }) => {
    dispatch(changePlaySongIndexAction(-1))
    dispatch(changeCurrentSongAction({}))
    dispatch(changePlaySongListAction([]))
    dispatch(changeLyricAction([]))
  }
)

// 清除一首歌曲
export const removeOneMusicAction = createAsyncThunk<
  void,
  number,
  { state: RootState }
>('removeOneMusic', (id: number, { dispatch, getState }) => {
  const player = getState().player
  const playList = player.playSongList.slice()
  let currentIndex = player.playSongIndex
  const fIndex = playList.findIndex((item: Song) => item.id === id)
  console.log(fIndex)
  playList.splice(fIndex, 1)
  if (currentIndex > fIndex || currentIndex === playList.length) {
    currentIndex--
  }
  const currentSong = playList[currentIndex]
  dispatch(changePlaySongListAction(playList))
  dispatch(changePlaySongIndexAction(currentIndex))
  dispatch(changeCurrentSongAction(currentSong))
  dispatch(changeLyricAction([]))
})

const initialState: IPlayerState = {
  currentSong: {
    id: 0,
    name: '',
    url: '',
    ar: [],
    al: {
      id: 0,
      name: '',
      picUrl: ''
    },
    dt: -1
  },
  playSongList: [],
  playSongIndex: -1,
  playMode: 0,
  lyrics: [],
  lyricIndex: -1
}

const playerSlice = createSlice({
  name: 'player',
  initialState,
  reducers: {
    changeCurrentSongAction(state, { payload }) {
      state.currentSong = payload
    },
    changeLyricAction(state, { payload }) {
      state.lyrics = payload
    },
    changeLyricIndexAction(state, { payload }) {
      state.lyricIndex = payload
    },
    changePlaySongListAction(state, { payload }) {
      state.playSongList = payload
    },
    changePlaySongIndexAction(state, { payload }) {
      state.playSongIndex = payload
    },
    changePlayModeAction(state, { payload }) {
      state.playMode = payload
    }
  }
})

export const {
  changeCurrentSongAction,
  changeLyricAction,
  changeLyricIndexAction,
  changePlaySongListAction,
  changePlaySongIndexAction,
  changePlayModeAction
} = playerSlice.actions

export default playerSlice.reducer
